package com.gzsxy.esjy.service.cart.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.gzsxy.esjy.common.base.exception.impl.CustomAssert;

import com.gzsxy.esjy.common.base.result.ResultCodeEnum;
import com.gzsxy.esjy.feign.Product.ProductFeignService;
import com.gzsxy.esjy.service.base.DictionaryConstants;
import com.gzsxy.esjy.service.base.dto.request.ApiCartRequest;
import com.gzsxy.esjy.service.base.dto.response.CartRsp;

import com.gzsxy.esjy.service.base.dto.response.DefaultResponse;
import com.gzsxy.esjy.service.base.dto.response.ProductRsp;
import com.gzsxy.esjy.service.cart.dao.CartMapper;
import com.gzsxy.esjy.service.cart.entity.Cart;
import com.gzsxy.esjy.service.cart.service.CartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;



/**
 * @author xiaolong
 * @version 1.0
 * @description: 购物车
 * @date 2022/2/17 17:46
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {


    @Autowired
    private ProductFeignService productFeignService;

    /**
     * @description: 根据用户id获取当前购物车
     * @param
     * @return
     */
    @Override
    public List<CartRsp> getCartByUserId(String userId) {
        return baseMapper.getCartByUserId(userId);
    }


    /**
     * @description: 根据用户id删除购物车
     * @param
     * @return
     */
    @Override
    public void deleteByUserId(String userId) {
        LambdaQueryWrapper<Cart> wrapper = Wrappers.lambdaQuery();
        
        wrapper.eq(Cart::getUserId,userId);
        baseMapper.delete(wrapper);
    }


    /**
     * @description: 前台根据用户获取购物车
     * @param
     * @return
     */
    @Override
    public List<CartRsp> getApiCart(String userId) {
        //通过session获取当前登录用户
//        UserRsp user = CurrentUserUtil.getUser();
//        //登录过期，请重新登录!
//        CustomAssert.notTrue(ObjectUtils.isNotEmpty(user), ResultCodeEnum.LOGIN_EXPIRED.getMessage());
        return baseMapper.getCartByUserId(userId);
    }


    /**
     * @description: 根据购物车id更新商品数量
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<CartRsp> editNumber(ApiCartRequest apiCartRequest) {
        Cart cart = baseMapper.selectById(apiCartRequest.getId());
        //该购物车不存在
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(cart), ResultCodeEnum.CART_NOT_EXIST_ERROR.getMessage());
        //远程查询当前商品是否存在，并判断当前库存是否允许添加
        DefaultResponse response = productFeignService.getProductById(apiCartRequest.getProductId());
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(response.getData()), ResultCodeEnum.PRODUCT_NOT_EXIST_ERROR.getMessage());
        ProductRsp productRsp = JSON.parseObject(JSON.toJSONString(response.getData()), ProductRsp.class);
        //如果购物车数量大于当前商品库存
        if (apiCartRequest.getNumber()>productRsp.getNumber()){
            CustomAssert.notTrue(false, ResultCodeEnum.PRODUCT_NUMBER_ERROR1.getMessage());
        }
        cart.setNumber(apiCartRequest.getNumber());
        baseMapper.updateById(cart);
        return baseMapper.getCartByUserId(apiCartRequest.getUserId());
    }


    /**
     * @description: 删除购物车
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCart(String id) {
        Cart cart = baseMapper.selectById(id);
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(cart),ResultCodeEnum.CART_NOT_EXIST_ERROR.getMessage());
        baseMapper.deleteById(cart);
    }


    /**
     * @description: 添加购物车
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addCart(ApiCartRequest apiCartRequest) {
        Cart cart = new Cart();
        BeanUtils.copyProperties(apiCartRequest,cart);
        //TODO 根据商品id查询是否存在该商品
        DefaultResponse response = productFeignService.getProductById(apiCartRequest.getProductId());
//        ProductRsp productRsp = JSON.parseObject(JSON.toJSONString(response.getData()), ProductRsp.class);
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(response.getData()),ResultCodeEnum.PRODUCT_NOT_EXIST_ERROR.getMessage());
        //TODO 查询当前用户的购物车，如果存在添加的商品，则数量加一
        LambdaQueryWrapper<Cart> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Cart::getUserId,apiCartRequest.getUserId());
        List<Cart> cartList = baseMapper.selectList(wrapper);
        Optional<Cart> first = cartList.stream().filter(cart1 -> cart1.getProductId().equals(apiCartRequest.getProductId())).findFirst();
        //如果Optional对象里面没有数据，直接调用Optional.get()会报错。
        //使用orElse()方法代替get()方法，orElse()方法的作用是当Optional对象里面没有数据时会使用orElse()方法里面的值。
        Cart cart1 = first.orElse(null);
        if (ObjectUtils.isNotEmpty(cart1)){
            cart1.setNumber(cart1.getNumber()+1);
            baseMapper.updateById(cart1);
        } else {
            cart.setNumber(DictionaryConstants.NUMBER_1);
            baseMapper.insert(cart);
        }

    }
}
